/* 
 * File:   logger.h
 * Author: alex
 *
 * Created on March 21, 2014, 6:08 PM
 */

#ifndef HEADER_H
#define	HEADER_H

#include <string>
#include <iostream>
#include <map>
#include <climits>
#include <cstring>
#include <ctime>
#include <fstream>
#include <cstdlib>
#include <sys/msg.h>

static int msgqid = 0;
const unsigned MSGTXTLEN = 1024;   // msg text length
const unsigned NAME_LEN = 42;
//NAME_LEN + sizeof(int) must be <= MSGTXTLEN

using namespace std;

enum {LOGOUT_TYPE = 1, INIT_TYPE, SUBS_TYPE, DEBUG_TYPE, WARNING_TYPE, ERROR_TYPE};
enum {RELEASE_MODE, DEBUG_MODE};

class Log {
public:
    Log(int mq, int mode, const char* name, int pid);
    Log(const Log& orig);
    virtual ~Log();
    int Debug(string  s);
    int Warning(string s);
    int Error(string s);
    int logout();
private:
    int m_msgqid;
    int m_mode;
    char m_name[NAME_LEN];
    int m_pid;
    

};

class Record {
public:
    char name[NAME_LEN];
    int id;
    int mode;

    Record(const char * n, int i, int m) {
        strncpy(name, n, NAME_LEN);
        id = i;
        mode = m;
    }
    Record(){};
};

class Logger{
public:
    static Log subs(int mode, const char name[NAME_LEN]);
    static int init(size_t buffsize = 1024*1024, const char* file = "log.txt");
private:
    static Logger * inst;
    
    char *buffer;
    size_t buf_start;
    size_t buf_ptr; //next after taken area
    size_t buf_size;
    ofstream *out;
    
    map<int, Record> processes;
    int m_msgqid;
    unsigned m_sleep_time;
    Logger();
    int buf_write(char name[NAME_LEN], char str[MSGTXTLEN], size_t len);
    int buf_dump();
};


struct init_buf{
    long mtype;
    struct{
        size_t buffsize;
        char file_name[PATH_MAX];
    } data;
};

struct subs_buf{
    long mtype;
    struct{
        int pid;
        int mode;
        char name[NAME_LEN];
    } data;
};

struct msg_buf{
    long mtype;
    struct{
        int pid;
        char mtext[MSGTXTLEN];
    } data;
};

//Log init(const char* name, int mode, size_t buffsize = 64, const char* file = "log.txt", size_t filesize = 1024);

#endif	/* HEADER_H */

